package com.ciwong.epaper.modules.me.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.view.View;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.adapter.OfflineCatalogAdapter;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.listview.SlideListView;

/**
 * 离线缓存子界面 Created by res-jianpingliu on 2015/7/24.
 */
public class OfflineCatalogActivity extends BaseActivity
{
    private SlideListView mListView;

    private OfflineCatalogAdapter mAdapter;

    private List<DownLoadInfo> mDownLoadInfos;

    private boolean isEditting, isCheckAll;

    private View delLayout;

    private List<DownLoadInfo> delList;

    private CWDialog dialog;

    private  int mServiceId;


    /**
     * 设置activity的布局文件
     *
     * @return 布局文件的resId
     */
    @Override
    protected int setView()
    {
        return R.layout.activity_offline_files;
    }

    /**
     * 获取界面元素
     */
    @Override
    protected void findViews()
    {
        mListView = (SlideListView) findViewById(R.id.offline_files_lv);
        delLayout = findViewById(R.id.offline_files_del_ll);
    }

    /**
     * 设置事件
     */
    @Override
    protected void initEvent()
    {
        setRightBtnListener(new ViewOnClickListener()
        {
            @Override
            public void avertRepeatOnClick(View v)
            {
                isEditting = !isEditting;
                if (isEditting)
                {
                    setRightBtnText(R.string.cancel);
                    delLayout.setVisibility(View.VISIBLE);
                }
                else
                {
                    setRightBtnText(R.string.compile);
                    delLayout.setVisibility(View.GONE);
                    clearDeleteList();
                }
                mAdapter.setEdit(isEditting);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void init()
    {
        mDownLoadInfos = new ArrayList<DownLoadInfo>();
        EventBus.getDownLoadInstance().register(this);
        setTitleText(
                getIntent().getStringExtra(BaseIntentFlag.INTENT_FLAG_STR));

        mDownLoadInfos = (ArrayList<DownLoadInfo>) getIntent()
                .getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ_LIST);
        mServiceId=getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID,-1);

        if (mDownLoadInfos != null)
        {
            mAdapter = new OfflineCatalogAdapter(this, mDownLoadInfos,
                    mListView);
            mListView.setAdapter(mAdapter);
            setRightBtnText(R.string.compile);
        }
    }

    @Override
    protected void loadData()
    {

    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        EventBus.getDownLoadInstance().unregister(this);
    }

    public void onItemClick(int position)
    {
        DownLoadInfo downLoadInfo = mDownLoadInfos.get(position);
        if (isEditting)
        {
            boolean isChecked = false;
            if (downLoadInfo.isCheck())
            {
                downLoadInfo.setIsCheck(false);
            }
            else
            {
                downLoadInfo.setIsCheck(true);
                isChecked = true;
            }
            checkItem(downLoadInfo, isChecked);
        }
        else
        {
            //隐藏点击做作业功能
            if (true)
            {
                return;
            }
            String packageDir = ESystem.getPackagesCatalogue(
                    downLoadInfo.getBookId(), downLoadInfo.getChapterId());
            ServiceDetail serviceDetail = ((EApplication) getBaseApplication())
                    .getServiceDetail();
            if (((serviceDetail == null || serviceDetail.isbExpired())
                    && downLoadInfo.getIsFree() == 0))
            {
                int serviceId = 0;
                String serviceName = null;
                if (serviceDetail != null)
                {
                    serviceId = serviceDetail.getServiceType();
                    serviceName = serviceDetail.getServiceTypeName();
                }
//                DialogUtil.showOpenServiceDialog2(this, serviceId,MainActivity.REQUEST_CODE_TO_PAY);
            }
            else
            {
                if (downLoadInfo.getStatus() == DownloadStatus.STATUS_COMPLETED
                        && new File(packageDir).exists())
                {
                    //电子报信息离线无法取得
                    EpaperJumpManager.jumpToContent(R.string.go_back,
                            OfflineCatalogActivity.this, downLoadInfo,mServiceId,null,null);
                }
                else
                {
                    List<DownLoadInfo> downLoadInfos = new ArrayList<DownLoadInfo>();
                    downLoadInfos.add(downLoadInfo);
                    DownLoad.getInstance().deletePackages(downLoadInfos);
                    mDownLoadInfos.remove(downLoadInfo);
                    mAdapter.notifyDataSetChanged();
                    showToastError(R.string.resource_file_not_exist);
                }
            }
        }
    }

    private void checkItem(DownLoadInfo info, boolean isc)
    {
        if (delList == null)
        {
            delList = new ArrayList<DownLoadInfo>();
        }

        if (isc)
        {
            if (!delList.contains(info))
            {
                delList.add(info);
            }
        }
        else
        {
            delList.remove(info);
        }
        mAdapter.notifyDataSetChanged();
    }

    public void setCheckAll(boolean isCheck)
    {
        for (int i = 0; i < mDownLoadInfos.size(); i++)
        {
            mDownLoadInfos.get(i).setIsCheck(isCheck);
            checkItem(mDownLoadInfos.get(i), isCheck);
        }
    }

    public void clearDeleteList()
    {
        if (delList != null)
        {
            for (DownLoadInfo info : delList)
            {
                if (info != null)
                {
                    info.setIsCheck(false);
                }
            }
            delList.clear();
        }
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item)
    {
        DownLoadInfo info = item.getInfo();
        if (info.getStatus() == DownloadStatus.STATUS_COMPLETED)
        {
            mDownLoadInfos.add(info);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void checkAll(View v)
    {
        isCheckAll = !isCheckAll;
        setCheckAll(isCheckAll);
        mAdapter.notifyDataSetChanged();
    }

    public void delete(View v)
    {
        if (delList == null || delList.isEmpty())
        {
            return;
        }
        if (mDownLoadInfos != null)
        {
            mDownLoadInfos.removeAll(delList);
        }
        if (mDownLoadInfos.isEmpty())
        {
            hideRightBtn();
            delLayout.setVisibility(View.GONE);
            finish();
        }
        mAdapter.notifyDataSetChanged();
        deleteFromLocation(delList);
    }

    public void deleteFromLocation(List<DownLoadInfo> list)
    {
        DownLoad.getInstance().deletePackages(list);
    }
}
